package com.jse.view;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.beetl.ext.nutz.BeetlViewMaker;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ForwardView;
import org.nutz.mvc.view.JspView;
import org.nutz.mvc.view.RawView;
import org.nutz.mvc.view.ServerRedirectView;
import org.nutz.mvc.view.UTF8JsonView;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

public class JseView implements View {

	private String value = "view";

	public JseView(String value) {
		this.value = value;
	}

	@Override
	public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
		String suffix = Mvcs.getActionContext().getSuffix().toLowerCase();
		String root = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getContextPath()
				+ "/";
		if (obj instanceof ScriptObjectMirror) {// 针对jjs的[object Array]类型转换
			ScriptObjectMirror som = ScriptObjectMirror.class.cast(obj);
			if (som.toString().equals("[object Array]")) {
				obj = Json.fromJson(ArrayList.class, Json.toJson(som));
			} else if (som.toString().equals("[object Object]")) {
				obj = NutMap.WRAP(som);
			}
		}
		if (req.getAttribute("_httpurl") != null) {
			String httpurl = req.getAttribute("_httpurl").toString();
			if (httpurl.contains("http")) {
				new ServerRedirectView(httpurl).render(req, resp, obj);
				return;
			} else {
				new ServerRedirectView(root + httpurl).render(req, resp, obj);
				return;
			}
		} else if (suffix.equals("xml")) {
			new RawView("text/xml").render(req, resp, obj);
			return;
		} else if (suffix.equals("jsonp")) {
			new UTF8JsonView().setJsonp(true).render(req, resp, obj);
			return;
		} else if (suffix.equals("jjs")) {
			//TODO Js 选项 对于字符串等操作可能会有问题 用到时再调整架构更新 
			StringBuffer sb=new StringBuffer();
			if(obj instanceof Map||obj instanceof List||obj instanceof Arrays)
				sb.append("var obj=").append(Json.toJson(obj));
			else
				sb.append("var obj= ").append(obj);
			Enumeration<String> attrs=req.getAttributeNames();
			while(attrs.hasMoreElements())   {   
			    String key=attrs.nextElement();   
			    Object val=req.getAttribute(key);
			    if(val instanceof Map||val instanceof List||obj instanceof Arrays)
					sb.append("var ").append(key).append(" = ").append(Json.toJson(val)).append(";\n");
				else
					sb.append("var ").append(key).append(" = ").append(val).append(";\n");
			}   
			new RawView("application/x-javascript").render(req, resp, sb);
			return;
		} else if (suffix.equals("json")) {
			new UTF8JsonView().render(req, resp, obj);
			return;
		} else if (Lang.contains(Lang.array("png", "jpg", "webp"), suffix)) {
			new RawView(suffix).render(req, resp, obj);
			return;
		} else if (Lang.contains(Lang.array("txt", "text"), suffix)) {// html/htm/jsp
			new RawView("text/plain").render(req, resp, obj);
			return;
		} else if (obj instanceof File) {// 文件以及下载
			new RawView("application/octet-stream").render(req, resp, obj);
			return;
		} else if (obj instanceof String) {
			String rtv = obj.toString().trim();
			if (rtv.startsWith("jsp:")) {
				new JspView(rtv.substring(4)).render(req, resp, obj);
				return;
			} else if (rtv.startsWith("json:")) {
				new UTF8JsonView().render(req, resp, Json.fromJson(rtv.substring(5)));
				return;
			} else if (rtv.startsWith("jsonp:")) {
				new UTF8JsonView().setJsonp(true).render(req, resp, rtv.substring(6));
				return;
			} else if (rtv.startsWith(">>:")) {
				new ServerRedirectView(root +rtv.substring(3)).render(req, resp, obj);
				return;
			} else if (rtv.startsWith("->:")) {
				new ForwardView(root +rtv.substring(3)).render(req, resp, obj);
				return;
			} else if (rtv.startsWith("http:")||rtv.startsWith("https:")) {
				new ServerRedirectView(rtv).render(req, resp, obj);
				return;
			} else {
				String path = req.getSession().getServletContext().getRealPath("");
				String fileName = req.getAttribute(value).toString() + ".html";
				if (Files.exists(Paths.get(path, fileName), LinkOption.NOFOLLOW_LINKS))
					new BeetlViewMaker().make(Mvcs.getIoc(), "beetl", fileName).render(req, resp, obj);
				else{
					new ServerRedirectView("/404.html").render(req, resp, obj);
					return;
				}
			}
		} else {// html
			String path = req.getSession().getServletContext().getRealPath("");
			String fileName = req.getAttribute(value).toString() + ".html";
			if (Files.exists(Paths.get(path, fileName), LinkOption.NOFOLLOW_LINKS))
				new BeetlViewMaker().make(Mvcs.getIoc(), "beetl", fileName).render(req, resp, obj);
			else{
				new ServerRedirectView("/404.html").render(req, resp, obj);
				return;
			}
		}

	}

}
